package dk.degofedal.android;

import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ToggleButton;

public class SeizureTrackerActivity extends Activity {
	
	private final static int START_WARMUP = 0;
	private final static int STOP_WARMUP = 1;
	private final static int SEIZURE = 2;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        ((ToggleButton)findViewById(R.id.toggleButton1)).setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if(isChecked) {
					registerEvent(System.currentTimeMillis(),0,START_WARMUP);
				} else {
					registerEvent(System.currentTimeMillis(),0,STOP_WARMUP);
				}
			}
		});
        
        final Button button = (Button) findViewById(R.id.button1);
		button.setOnTouchListener(new OnTouchListener() {
			
        	long timer = 0;
        	
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if(event.getAction() == MotionEvent.ACTION_DOWN) {
		            //increaseSize();
					button.setPressed(true);
					timer = System.currentTimeMillis();
		        } else if (event.getAction() == MotionEvent.ACTION_UP) {
		            //resetSize();
		        	long stopTimer = System.currentTimeMillis();
		        	registerEvent(stopTimer, stopTimer-timer, SEIZURE);
					button.setPressed(false);
		        }
				return true;
			}
		});
        
        ensureLogFile();
    }
    
    private void ensureLogFile() {
    	File baseDir = new File(Environment.getExternalStorageDirectory(),"SeizureTracker");
    	if(!baseDir.exists()) {
    		baseDir.mkdir();
    	}
    }
    
    private void registerEvent(long eventTime, long duration, int type) {
    	// open file
    	// write
    	// close file
    	File baseDir = new File(Environment.getExternalStorageDirectory(),"SeizureTracker");
    	
    	try {
    		FileWriter printWriter = new FileWriter(new File(baseDir, "seizure.log"), true);
    		printWriter.append(eventTime + "|" + duration + "|" + type +"\n");
    		printWriter.close();
    	} catch (Exception e) {
    		e.printStackTrace();
		}
    }
}